package com.lins.msm.bo.impl;

import com.alibaba.druid.util.StringUtils;
import com.lins.common.util.RandomUtil;
import com.lins.msm.ConstantPropertiesUtils;
import com.lins.msm.bo.MsmService;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.sms.v20210111.SmsClient;
import com.tencentcloudapi.sms.v20210111.models.SendSmsRequest;
import com.tencentcloudapi.sms.v20210111.models.SendSmsResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @Author linshuo
 * @Date 2022/11/17 15:00
 * 腾讯云的短信服务
 */
@Slf4j
@Service("tencentMsmService")
public class TencentMsmService implements MsmService {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 准备发送验证码
     * return:
     *  0：发送失败
     *  1：发送成功
     *  2：发送失败，刚刚发送过
     **/
    @Override
    public int sendReady(String phone, String yxq) {
        //先从redis根据手机号获取验证码
        String code = redisTemplate.opsForValue().get(phone);
        if(!StringUtils.isEmpty(code)) return 2;
        //如果从redis获取不到，生成验证码，通过短信服务发送
        code = RandomUtil.getSixBitRandom();
        boolean isSend = this.send(phone,code,yxq);
        if(isSend) {
            //生成验证码放到redis里面，设置有效时间
            redisTemplate.opsForValue().set(phone, code, Integer.valueOf(yxq), TimeUnit.MINUTES);
            return 1;
        } else {
            return 0;
        }
    }

    @Override
    public boolean send(String phone, String code,String yxq) {
        try {
            //实例化Credential证书，也就是认证对象，参数是密钥对
            Credential credential = new Credential(ConstantPropertiesUtils.SECRET_ID, ConstantPropertiesUtils.SECRET_KEY);
            //HttpProfile是http的配置文件操作，比如设置请求类型(post,get)或者设置超时时间、指定域名
            //最简单的就是实例化该对象即可，它的构造方法已经帮我们设置了一些默认的值
            HttpProfile httpProfile = new HttpProfile();
            //实例化客户端配置对象,这个配置可以进行签名（使用私钥进行加密的过程），对方可以利用公钥进行解密
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);
            //实例化要请求产品(以sms为例)的client对象
            SmsClient smsClient = new SmsClient(credential, "ap-nanjing", clientProfile);
            //实例化request封装请求信息
            SendSmsRequest request = new SendSmsRequest();
            //设置手机号
            request.setPhoneNumberSet(new String[]{phone});
            request.setSmsSdkAppId(ConstantPropertiesUtils.APP_ID);
            request.setSignName("小象憨憨个人网");
            request.setTemplateId(ConstantPropertiesUtils.TEMPLATE_ID);
            //设置验证码
            request.setTemplateParamSet(new String[]{code, yxq});
            //发送短信，并收到响应
            SendSmsResponse response = smsClient.SendSms(request);
            //输出json格式的字符串回包
            log.info(SendSmsResponse.toJsonString(response));
            return true;
        } catch (Exception e) {
            log.error(e.toString());
            return false;
        }
    }
}
